package com.huixin.zhang.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringSubstitutor;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串工具类
 *
 * @author Toltech
 * @date Sep 1, 2018
 */
@Slf4j
public class TextUtils {
    public static String[] chars = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p",
            "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A",
            "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
            "W", "X", "Y", "Z"};

    public static String toUtf8Encode(String s) {
        String r = null;
        if (s != null) {
            try {
                r = URLEncoder.encode(s, "UTF-8");
            } catch (Exception e) {
                log.error("字符转换utf-8编码异常,{}", e);
            }
        }
        return r;
    }

    public static String toUtf8Decode(String s) {
        String r = null;
        if (s != null) {
            try {
                r = URLDecoder.decode(s, "UTF-8");
            } catch (Exception e) {
                e.printStackTrace();
                log.error("utf-8字符解码异常,{}", e);
            }
        }
        return r;
    }

    /**
     * 判空操作
     *
     * @param value
     * @return
     */
    public static boolean isBlank(String value) {
        return value == null || "".equals(value) || "null".equals(value) || "undefined".equals(value);
    }

    public static boolean isNotBlank(String value) {
        return !isBlank(value);
    }

    public static String generateShortUuid() {
        StringBuffer shortBuffer = new StringBuffer();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        for (int i = 0; i < 8; i++) {
            String str = uuid.substring(i * 4, i * 4 + 4);
            int x = Integer.parseInt(str, 16);
            shortBuffer.append(chars[(x % 62)]);
        }
        return shortBuffer.toString();
    }

    public static String getSubString(String content, int firstLength, int lastLength, String split) {
        String temp = "";
        if ((isNotNULL(content)) && (content.length() > firstLength + lastLength)) {
            temp = content.substring(0, firstLength)
                    + getRepeatString(split, content.length() - firstLength - lastLength)
                    + content.substring(content.length() - lastLength);
        }

        return temp;
    }

    public static String getRepeatString(String split, int count) {
        StringBuffer generateRandStr = new StringBuffer();
        for (int i = 0; i < count; i++) {
            generateRandStr.append(split);
        }
        return generateRandStr.toString();
    }

    public static boolean isNotNULL(String params) {
        return (params != null) && (!"".equals(params));
    }

    public static String removeSpecialChar(String sourceStr) {
        if (StringUtils.isBlank(sourceStr))
            return "";
        return sourceStr.replace(" ", "").replace("。", "").replace("、", "").replace(",", "").replace("，", "")
                .replaceAll("[\\t]", "").replaceAll("[\\r]", "").replaceAll("[\\n]", "").replaceAll("[\"]", "");
    }

    public static String removeSpecialCharAll(String sourceStr) {
        if (StringUtils.isBlank(sourceStr))
            return "";
        return sourceStr.replace(" ", "").replace("。", "").replace("~", "").replace("`", "").replace("、", "")
                .replace(",", "").replace("/", "").replace("!", "").replace("$", "").replace("*", "").replace("+", "")
                .replace("-", "").replace("=", "").replace("|", "").replace("[", "").replace("]", "").replace("{", "")
                .replace("}", "").replace("'", "").replace("<", "").replace(">", "").replace("?", "").replace("@", "")
                .replace("#", "").replace("%", "").replace("^", "").replace("，", "").replaceAll("[\\t]", "")
                .replaceAll("[\\r]", "").replaceAll("[\\n]", "").replaceAll("[\"]", "");
    }

    public static String getRandomUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * 自定义渲染模板
     *
     * @param template 模版
     * @param params   参数
     * @return
     */
    public static String renderString(String template, Map<String, String> params) {
        StringSubstitutor strSubstitutor = new StringSubstitutor(params);
        return strSubstitutor.replace(template);
    }

    public static String renderString(String template, String name, String value) {
        if (StringUtils.isAnyBlank(template, name, value)) {
            return null;
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put(name, value);
        StringSubstitutor strSubstitutor = new StringSubstitutor(map);
        return strSubstitutor.replace(template);
    }


    public static boolean isMobile(String text) {
        if (text.length() != 11) {
            return false;
        }
        String regex = "^((13[0-9])|(14[0-9])|(15([0-9]))|(166)|(17[0-9])|(18[0-9])|(19[0-9]))\\d{8}$";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(text);
        boolean match = m.matches();
        return match;
    }

    public static String replaceBlank(String text) {
    	if(StringUtils.isBlank(text)){
    		return text;
		}
        String dest = "";
		Pattern p = Pattern.compile("\\s*|\t|\r|\n");
		Matcher m = p.matcher(text);
		dest = m.replaceAll("");
		return dest;
    }
}
